package itsm.isperp.framework.security.access.intercept;

import itsm.isperp.framework.core.context.ContextHolder;

import java.util.Collection;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

/**
 * 加载所有需要权限管制的URL资源
 * 
 * @since 1.0
 */
public class UrlSecurityMetadataSourceService implements InitializingBean,
		FilterInvocationSecurityMetadataSource {

	private String specialUrlAccessDefinition;

	public void afterPropertiesSet() throws Exception {

		ContextHolder.reloadAuthorityResourceDefinition();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.security.access.SecurityMetadataSource#getAttributes
	 * (java.lang.Object)
	 */
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {

		String url = null;
		if (object instanceof FilterInvocation) {
			url = ((FilterInvocation) object).getRequestUrl();
		} else {
			url = (String) object;
		}
		if (url.startsWith("/")) {
			url = url.substring(1, url.length());
		}

		return ContextHolder.getAuthorityResourceDefinition().get(url);

	}

	public String getSpecialUrlAccessDefinition() {
		return specialUrlAccessDefinition;
	}

	public void setSpecialUrlAccessDefinition(String specialUrlAccessDefinition) {
		this.specialUrlAccessDefinition = specialUrlAccessDefinition;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {

		return true;
	}
}
